/**
 * Xinfei.com Inc.
 * Copyright (c) 2004-2023 All Rights Reserved.
 */
package com.xinfei.techplayprod.biz.code;

import com.xinfei.techplayprod.biz.mq.MqService;
import com.xinfei.techplayprod.biz.rr.TestResponse;
import com.xinfei.techplayprod.itl.PhpFeinClient;
import com.xinfei.techplayprod.itl.rr.TeamQueryRequest;
import com.xinfei.techplayprod.itl.rr.TeamQueryResponse;
import com.xinfei.xfframework.common.IPUtil;
import com.xinfei.xfframework.common.Util;
import com.xinfei.xfframework.context.Context;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

/**
 * 代码生成器<br/>
 *
 * @author Chengsheng.Li
 * @version $ CodeGenController, v 0.1 2023/8/30 18:11 Chengsheng.Li Exp $
 */
@RestController
@RequestMapping("/code")
public class CodeGenController {
    @Autowired
    private CodeGenUtil copyUtil;

    @Autowired
    private MqService mqService;

    @Autowired
    private PhpFeinClient phpFeinClient;
    private OkHttpClient okHttpClient = new OkHttpClient();

    @Value("${gw.test.url:}")
    public String url;
    @Value("${gw.test.host:}")
    public String host;

    @RequestMapping("/gwtest")
    public String apptest() throws IOException {
        Request.Builder builder = new Request.Builder();
        builder.url(url).header("host", host);
        builder.header("app","gwtest");
        builder.header("innerapp","gwtest");
        builder.header("token","123456789");
        Response response = null;
        try {
             response= okHttpClient.newCall(builder.build()).execute();
            return response.body().string();
        }finally {
            if(response!=null){
                response.close();
            }
        }
    }
    @RequestMapping("/gwtest1")
    public String apptest1() throws IOException {
        Request.Builder builder = new Request.Builder();
        builder.url(url).header("host", host);
        builder.header("xf-context-path","/test");
        builder.header("app","gwtest");
        builder.header("innerapp","gwtest");
        builder.header("token","123456789");
        Response response = null;
        try {
            response= okHttpClient.newCall(builder.build()).execute();
            return response.body().string();
        }finally {
            if(response!=null){
                response.close();
            }
        }
    }

    @RequestMapping("/gwdemo")
    public String gwdemo() throws IOException {
        return Context.APP_NAME;
    }

    @RequestMapping("/httptest")
    public TeamQueryResponse testPhpFeinClient() {
        TeamQueryRequest teamQueryRequest=new TeamQueryRequest();
        teamQueryRequest.setTeamCode("test");
        return phpFeinClient.queryByCode(teamQueryRequest);
    }

    @RequestMapping("/mqtopicgroup")
    public String getMqTopicGroup() {
        return mqService.getTopicConsumerGroup();
    }
    Random random=new Random();
    @RequestMapping("/test")
    public String test(HttpServletRequest request){
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL().toString());
        System.out.println(request.getQueryString());
        System.out.println(request.getServerName());

        if(StringUtils.hasText(request.getParameter("t"))){
          Util.sleep(Integer.parseInt(request.getParameter("t")));
        }
        if(StringUtils.hasText(request.getParameter("t2"))){
           if(random.nextInt(10)%2==0){
               throw new RuntimeException();
           }
        }
        StringBuilder sr=new StringBuilder();

        if(StringUtils.hasText(request.getParameter("t1"))){
            int t1=Integer.parseInt(request.getParameter("t1"));
            for (int i=0;i<t1;i++){
                sr.append("15821804125,15821804126,");
            }
            return sr.toString();
        }
        return "15821804125,15821804126";
    }
    @RequestMapping("/ip")
    public String getIp() {
        return IPUtil.getLocalIP();
    }

    @RequestMapping(value = "/gen", method = RequestMethod.GET)
    public ResponseEntity<Resource> gen(@RequestParam String appName, @RequestParam int type) throws IOException {

        // Load file as Resource
        //Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
        String path = copyUtil.gen(appName, type, null);
        File file = new File(path);

        // Convert the file path to a URI
        URI uri = file.toURI();
        Path filePath = Paths.get(uri);

        Resource resource = new UrlResource(filePath.toUri());

        // Determine the file's media type
        String contentType = "application/octet-stream";
//        try {
//            contentType = Files.probeContentType(filePath);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);


    }
}